package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionsService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//权限管理模块
@RestController
@RequestMapping("/permissions")
public class PermissionsConttroller {

    @Reference
    private PermissionsService permissionsService;
    //初始化:放权限关键字
    private List<Permission> keyList = new ArrayList<>();

    //分页查询权限
    @RequestMapping(value = "/findPage", method = RequestMethod.POST)
    public PageResult findPage(@RequestBody QueryPageBean pageBean) {
        try {
            if (keyList == null || keyList.size() <= 0) {
                //将权限关键字存入List集合
                List<Permission> list = permissionsService.queryAllPermissions();
                if (list != null && list.size() > 0) {
                    for (Permission permission : list) {
                        keyList.add(permission);
                    }
                }
            }
            return permissionsService.findPage(pageBean.getQueryString(), pageBean.getPageSize(), pageBean.getCurrentPage());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //添加时校验权限名称和关键字
    @RequestMapping(value = "/addVerifyThePermissionKeyword", method = RequestMethod.POST)
    public Result addVerifyThePermissionKeyword(@RequestBody Permission permissions) {
        ////编辑时校验权限关键字和名称
        return verifyPermissionNameAndKeyword(permissions);
    }

    /**
     * 添加权限
     * @param permission
     * @return
     */
    @RequestMapping(value = "/addPermissions", method = RequestMethod.POST)
    public Result addPermissions(@RequestBody Permission permission) {
        try {
            //执行添加功能
            permissionsService.addPermissions(permission);
            //根据权限名和权限关键字查询权限，并加入集合
            Permission queryPermission = permissionsService.queryPermission(permission.getName(), permission.getKeyword());
            //添加到集合
            keyList.add(queryPermission);
            //返回集合中id
            return new Result(true, MessageConstant.INSERT_PERMISSION_SUCCESS, queryPermission.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.INSERT_PERMISSION_FAIL);
        }
    }

    //回显权限
    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    public Permission findById(Integer permissionsId, HttpServletRequest request) {
        try {
            Permission permission = permissionsService.findById(permissionsId);
            if (permission != null) {
                request.getSession().setAttribute("permission", permission);
            }
            return permission;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //编辑时校验权限关键字和名称
    @RequestMapping(value = "/editVerifyThePermissionKeyword", method = RequestMethod.POST)
    public Result editVerifyThePermissionKeyword(@RequestBody Permission permissionNew, HttpServletRequest request) {
        Permission permissionOld = (Permission) request.getSession().getAttribute("permission");
        if (permissionOld != null) {
            if ((permissionOld.getDescription() == null && permissionNew.getDescription() != null) || (permissionOld.getDescription() != null && permissionNew.getDescription() == null)) {
                return new Result(true, "");
            } else if (permissionOld.getDescription() == null && permissionNew.getDescription() == null) {
                return theKeywordAndNameAreCheckedToSeeIfTheyAreTheSame(permissionNew, permissionOld);
            } else if (permissionOld.getDescription() != null && permissionNew.getDescription() != null) {
                if (permissionOld.getDescription().equals(permissionNew.getDescription())) {
                    return theKeywordAndNameAreCheckedToSeeIfTheyAreTheSame(permissionNew, permissionOld);
                } else {
                    return new Result(true, "");
                }
            }
        }
        return null;
    }

    //编辑时校验权限关键字和名称
    private Result theKeywordAndNameAreCheckedToSeeIfTheyAreTheSame(@RequestBody Permission permissionNew, Permission permissionOld) {
        if (permissionOld.getName().equals(permissionNew.getName()) && permissionOld.getKeyword().equals(permissionNew.getKeyword())) {
            return new Result(false, MessageConstant.PERMISSIONNEW_KEYWORD_FAIL, MessageConstant.PERMISSIONNEW_NAME_FAIL);
        } else {
            if (keyList != null && keyList.size() > 0) {
                for (Permission permission : keyList) {
                    if (!permissionOld.getName().equals(permissionNew.getName()) && !permissionOld.getKeyword().equals(permissionNew.getKeyword())) {
                        if (permission.getKeyword().equals(permissionNew.getKeyword()) && permission.getName().equals(permissionNew.getName())) {
                            return new Result(false, MessageConstant.PERMISSION_KEYWORD_FAIL, MessageConstant.PERMISSION_NAME_FAIL);
                        }
                    }
                    if (!permissionOld.getKeyword().equals(permissionNew.getKeyword())) {
                        if (permission.getKeyword().equals(permissionNew.getKeyword())) {
                            return new Result(false, MessageConstant.PERMISSION_KEYWORD_FAIL, null);
                        }
                    }
                    if (!permissionOld.getName().equals(permissionNew.getName())) {
                        if (permission.getName().equals(permissionNew.getName())) {
                            return new Result(false, null, MessageConstant.PERMISSION_NAME_FAIL);
                        }
                    }
                }
            }
        }
        return new Result(true, "");
    }

    /**
     * 编辑权限
     * @param permission
     * @param request
     * @return
     */
    @RequestMapping(value = "/editPermissions", method = RequestMethod.POST)
    public Result editPermissions(@RequestBody Permission permission, HttpServletRequest request) {
        try {
            //执行功能
            int count = permissionsService.editPermissions(permission);
            if (count > 0) {
                //Session未修改权限
                Permission permissionSession = (Permission) request.getSession().getAttribute("permission");
                if (permissionSession != null) {
                    //删除集合中的关键字
                    removeListPermission(permissionSession);
                    keyList.add(permission);
                }
            }
            return new Result(true, MessageConstant.UPDATE_PERMISSION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.UPDATE_PERMISSION_FAIL);
        }
    }

    //查看此权限是否关联角色
    @RequestMapping(value = "/findPermissionsQueryRole", method = RequestMethod.GET)
    public boolean findPermissionsQueryRole(Integer id) {
        int count = permissionsService.findPermissionsQueryRole(id);
        return count <= 0;
    }

    //根据权限id查询角色
    @RequestMapping(value = "/handleQueryRole", method = RequestMethod.GET)
    public List<Map<String, String>> handleQueryRole(Integer permissionsId) {
        try {
            return permissionsService.handleQueryRole(permissionsId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除权限
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteByPermissionsId", method = RequestMethod.GET)
    public Result deleteByPermissionsId(Integer id) {
        try {
            //执行方法
            permissionsService.deleteByPermissionsId(id);

            //集合中的删除内容
            if (keyList != null && keyList.size() > 0) {
                for (Permission permissionList : keyList) {
                    if (id.equals(permissionList.getId())) {
                        keyList.remove(permissionList);
                        break;
                    }
                }
            }
            return new Result(true, MessageConstant.DELETE_PERMISSION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_PERMISSION_FAIL);
        }
    }

    //从list集合中删除权限
    private void removeListPermission(Permission permissionSession) {
        if (keyList != null && keyList.size() > 0) {
            for (Permission permissionList : keyList) {
                if (permissionList.getName().equals(permissionSession.getName()) && permissionList.getKeyword().equals(permissionSession.getKeyword())) {
                    keyList.remove(permissionList);
                    return;
                }
            }
        }
    }

    //添加时校验权限名称和关键字
    private Result verifyPermissionNameAndKeyword(@RequestBody Permission permissions) {
        if (keyList != null && keyList.size() > 0) {
            for (Permission permission : keyList) {
                if (permission != null) {
                    //判断是否有重复关键字
                    if (permission.getKeyword().equals(permissions.getKeyword()) && permission.getName().equals(permissions.getName())) {
                        return new Result(false, MessageConstant.PERMISSION_KEYWORD_FAIL, MessageConstant.PERMISSION_NAME_FAIL);
                    }
                    if (permission.getKeyword().equals(permissions.getKeyword())) {
                        return new Result(false, MessageConstant.PERMISSION_KEYWORD_FAIL, null);
                    }
                    if (permission.getName().equals(permissions.getName())) {
                        return new Result(false, null, MessageConstant.PERMISSION_NAME_FAIL);
                    }
                }
            }
        }
        return new Result(true, "");
    }

    //绑定角色
    @RequestMapping(value = "/handleEditUser", method = RequestMethod.POST)
    public Result handleEditUser(@RequestBody Map<String, Integer> map, Integer[] roleIds) {
        try {
            permissionsService.handleEditUser(map, roleIds);
            return new Result(true, "绑定角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "绑定角色失败");
        }
    }

}
